# This is a sample Python script.
import time

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
from googletrans import Translator
import xml.etree.ElementTree as ET

from LocalMap import ValueLocalMap
from XmlTool import find_string_content_by_name, insert_translation


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# values文件夹的绝对路径
#valuesPath = 'C:/root/projects/android/BodyScale/app/src/main/res/values'


valuesPath = 'C:/root/dev/zk/BodyScale/app/src/main/res/values'


# 根据语言编码获取strings.xml路径
def get_string_path_by_local(local):
    tem_path = valuesPath + '-' + local
    if local == '':
        tem_path = valuesPath

    tem_path += '/strings.xml'
    return tem_path


translator = Translator()


def translate(text: str, src_local: str, dest_local: str):
    """
    翻译方法
    :param text:需要翻译的文本
    :param src_local: 源values目录
    :param dest_local: 模板values目录
    :return: 返回Translated对象
    """
    return translator.translate(text, dest=ValueLocalMap[dest_local], src=ValueLocalMap[src_local])


baseLocal = ''

basePath = get_string_path_by_local(baseLocal)

# enPath = get_string_path_by_local('en')
# print(f"enPath={enPath}")

tree = ET.parse(basePath)
root = tree.getroot()

for string in root.findall('string'):
    name = string.get("name", "")
    content = string.text
    translatable = string.get("translatable", "")
    if translatable != 'false':
        # print(f'name={name},translatable={translatable}')
        for key, value in ValueLocalMap.items():
            # 排除基准语言
            if key != baseLocal:
                # print(f"{key}: {value}")
                targetPath = get_string_path_by_local(key)
                targetContent = find_string_content_by_name(targetPath, name)
                # 缺失的标签才翻译
                if targetContent is None:
                    result = translate(content, baseLocal, key)
                    print(f'name={name},local={key},content={content},targetContent={result.text}')
                    insert_translation(targetPath, name, result.text)
                    time.sleep(1)

# print(ValueLocalMap["zh-rTW"])
#
# result = translator.translate('语言', dest=ValueLocalMap["zh-rTW"], src=ValueLocalMap[""])
#
# print(result.text)
